package com.devunion.salon.persistence.dao;

import com.devunion.salon.persistence.CashInOut;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.io.Serializable;
import java.sql.Date;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Viktar Liaskovich
 */
public class CashInOutDao extends BaseDaoObject<CashInOut> {
    public CashInOut getByKey(Serializable key) {
        return (CashInOut) getHibernateTemplate().get(CashInOut.class, key);
    }

    public Set<CashInOut> getCashByDate(final Date date, final String username) {
        return (Set<CashInOut>) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List<CashInOut> result = session.createQuery("select cash from CashInOut cash, Login login where " +
                        "login.login = :username and cash.location = login.location and cash.created = :created")
                        .setParameter("username", username, Hibernate.STRING)
                        .setParameter("created", date, Hibernate.DATE)
                        .list();

                return result == null || result.isEmpty() ? new HashSet<CashInOut>() : new HashSet<CashInOut>(result);
            }
        });
    }

    public CashInOut getCashByNumber(final String username, final String number) {
        return (CashInOut) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                return session.createQuery("select cash from CashInOut cash, Login login where " +
                        "login.login = :username and cash.location = login.location and cash.number = :number")
                        .setParameter("username", username, Hibernate.STRING)
                        .setParameter("number", number, Hibernate.STRING)
                        .uniqueResult();                
            }
        });
    }
}